package com.example.interceptor;

import com.example.aspect.annotation.AllowAnon;
import com.example.exception.ServiceException;
import com.example.service.RedisService;
import com.example.utils.JwtUtil;
import com.example.utils.ResultCodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    private RedisService service;

    @Autowired
    public LoginInterceptor(RedisService service) {
        this.service = service;
    }


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (handler instanceof HandlerMethod) {
            HandlerMethod method = (HandlerMethod) handler;
            AllowAnon myOperation = method.getMethodAnnotation(AllowAnon.class);
            if (myOperation != null) {
                return true;
            }
        }
        /**
         * 校验请求头是否包含token
         */
        String token = request.getHeader("token");

        if (token == null || token.isEmpty()) {
            throw new ServiceException(ResultCodeUtil.NOT_LOGIN, "token不存在");
        }
        /**
         * 校验token是否过期
         */
        String verify = JwtUtil.verify(token);
        if (verify == null || verify.isEmpty()) {
            throw new ServiceException(ResultCodeUtil.VALIDATION_ERROR);
        }

//        User parse = JsonUtil.parse(verify, User.class);
//        if (parse != null) {
//            String tokenRedis = (String) service.get(TokenConstant.TOKEN_REDIS + parse.getUserName());
//            if (tokenRedis == null || tokenRedis.isEmpty()) {
//                throw new ServiceException(ResultCodeUtil.NOT_LOGIN, "token不存在");
//            }
//            if (!tokenRedis.equals(token)) {
//                throw new ServiceException(ResultCodeUtil.NOT_LOGIN, "token不存在");
//            }
//        }
        return true;
    }


}